package com.zj003.module.sys.service.impl;

import com.zj003.common.domain.entity.SysDept;
import com.zj003.module.sys.mapper.SysDeptMapper;
import com.zj003.module.sys.service.SysDeptService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author RedName
 * @description 针对表【sys_dept(部门表)】的数据库操作Service实现
 * @createDate 2022-05-01 03:30:07
 */
@Service
@RequiredArgsConstructor
public class SysDeptServiceImpl implements SysDeptService {

    private final SysDeptMapper deptMapper;

    @Override
    public List<SysDept> selectDeptList(SysDept dept) {
        dept.setDelFlag("0");
        return deptMapper.selectDeptList(dept);
    }

    @Override
    public List<SysDept> selectDeptTree() {
        List<SysDept> depts = deptMapper.selectDeptList(null);

        List<SysDept> collect = depts.stream().filter(dept -> dept.getParentId() == 0)
            .peek(dept -> dept.setChildren(findChildren(dept, depts)))
            .sorted(Comparator.comparingInt(dept -> Optional.ofNullable(dept.getOrderNum()).orElse(0)))
            .collect(Collectors.toList());

        return collect;
    }

    private List<SysDept> findChildren(SysDept root, List<SysDept> depts) {
        return depts.stream().filter(dept -> root.getDeptId().longValue() == dept.getParentId().longValue())
            .peek(dept -> dept.setChildren(findChildren(dept, depts)))
            .sorted(Comparator.comparingInt(dept -> Optional.ofNullable(dept.getOrderNum()).orElse(0)))
            .collect(Collectors.toList());

    }

    @Override
    public SysDept selectDeptByDeptId(Long deptId) {
        return deptMapper.selectDeptByDeptId(deptId);
    }

    @Override
    public void insertDept(SysDept dept) {
        deptMapper.insert(dept);
    }

    @Override
    public void updateDept(SysDept dept) {
        deptMapper.updateSelective(dept);

    }

    @Override
    public void deleteDept(Long deptId) {
        SysDept dept = new SysDept();
        dept.setDelFlag("1");
        dept.setDeptId(deptId);
        deptMapper.updateSelective(dept);

        //deptMapper.deleteByDeptId(deptId);
    }
}
